import { useMemo, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import dayjs from 'dayjs'
import { ClipboardDocumentListIcon, UserPlusIcon } from '@heroicons/react/24/outline'

import { RelationshipAPI } from '../app/api'
import type { ApiRelationship } from '../app/types'
import useCurrentUser from '../app/hooks/useCurrentUser'
import PageHeader from '../components/PageHeader'
import Button from '../components/ui/Button'
import { KebabMenu } from '../components/ui/Menu'
import SwipeableItem from '../components/ui/SwipeableItem'

const RelationshipsPage = () => {
  if (typeof document !== 'undefined') document.title = '情侣匹配 · Love Notes'
  const queryClient = useQueryClient()
  const { data: relationships = [], isLoading } = useQuery({
    queryKey: ['relationships'],
    queryFn: RelationshipAPI.listMine,
  })
  const { data: currentUser } = useCurrentUser()

  const inviteMutation = useMutation({
    mutationFn: RelationshipAPI.invite,
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['relationships'] })
      queryClient.invalidateQueries({ queryKey: ['me'] })
      setInviteCode(data.invite_code)
    },
  })

  const joinMutation = useMutation({
    mutationFn: RelationshipAPI.join,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['relationships'] })
      queryClient.invalidateQueries({ queryKey: ['me'] })
    },
  })

  const leaveMutation = useMutation({
    mutationFn: RelationshipAPI.leave,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['relationships'] })
      queryClient.invalidateQueries({ queryKey: ['me'] })
    },
  })

  const activeRelationship = useMemo(
    () => relationships.find((item) => item.status === 'active'),
    [relationships],
  )
  const pendingRelationship = useMemo(
    () => relationships.find((item) => item.status === 'pending'),
    [relationships],
  )

  const [inviteCode, setInviteCode] = useState('')
  const [copyHint, setCopyHint] = useState<string | null>(null)

  const handleCopy = async (code: string) => {
    try {
      await navigator.clipboard.writeText(code)
      setCopyHint('邀请码已复制')
    } catch {
      setCopyHint('复制失败，请手动复制')
    } finally {
      setTimeout(() => setCopyHint(null), 2000)
    }
  }

  const hasActiveRelationship = Boolean(activeRelationship ?? currentUser?.active_relationship_id)

  return (
    <div className="space-y-6">
      <PageHeader
        eyebrow="Relationships"
        title="情侣空间绑定"
        description="绑定情侣账号即可共享日记、纪念日、生理周期等数据，AI 对话也会按照双方历史持续进化。"
        rightSlot={
          <span
            className={`inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold ${
              hasActiveRelationship ? 'bg-emerald-100 text-emerald-600' : 'bg-amber-100 text-amber-600'
            }`}
          >
            状态：{hasActiveRelationship ? '已连接' : '待邀请'}
          </span>
        }
      />

      {!hasActiveRelationship ? (
        <InviteCard
          inviteCode={inviteCode || pendingRelationship?.invite_code || ''}
          copyHint={copyHint}
          onCreateInvite={() => inviteMutation.mutate()}
          onCopy={handleCopy}
          onJoin={(code) => joinMutation.mutate(code)}
          loadingInvite={inviteMutation.isPending}
          loadingJoin={joinMutation.isPending}
        />
      ) : (
        <section className="rounded-3xl border border-slate-100 bg-white/95 p-6 shadow-card">
          <h3 className="text-sm font-semibold text-slate-900">当前情侣空间</h3>
          <p className="mt-2 text-sm text-slate-500">
            你们的日记、纪念日、AI 对话与生理周期均在共享中。如需更换对象，可在下方关系记录解除绑定。
          </p>
        </section>
      )}

      <section className="rounded-3xl border border-slate-100 bg-white/95 p-6 shadow-card">
        <h3 className="text-sm font-semibold text-slate-900">关系记录</h3>
        <p className="text-xs text-slate-500">记录每一次绑定与解除操作，保留情侣空间的成长轨迹。</p>
        <div className="mt-5 space-y-3 text-sm text-slate-600">
          {isLoading ? (
            <p className="text-slate-400">加载中...</p>
          ) : relationships.length === 0 ? (
            <p className="text-slate-400">尚未创建情侣关系。</p>
          ) : (
            relationships.map((relationship) => (
              <RelationshipRow key={relationship.id} relationship={relationship} onLeave={leaveMutation.mutate} />
            ))
          )}
        </div>
      </section>
    </div>
  )
}

const InviteCard = ({
  inviteCode,
  copyHint,
  onCreateInvite,
  onCopy,
  onJoin,
  loadingInvite,
  loadingJoin,
}: {
  inviteCode: string
  copyHint: string | null
  onCreateInvite: () => void
  onCopy: (code: string) => void
  onJoin: (code: string) => void
  loadingInvite: boolean
  loadingJoin: boolean
}) => {
  const [joinCode, setJoinCode] = useState('')

  return (
    <section className="rounded-3xl border border-slate-100 bg-white/95 p-6 shadow-card">
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div>
          <h3 className="text-sm font-semibold text-slate-900">邀请绑定</h3>
          <p className="text-sm text-slate-500">生成邀请码或输入对方的邀请码，几秒完成情侣空间绑定。</p>
        </div>
        <Button
          onClick={onCreateInvite}
          variant="primary"
          size="sm"
          icon={<UserPlusIcon className="h-4 w-4" />}
          disabled={loadingInvite}
        >
          {loadingInvite ? '生成中...' : '生成我的邀请码'}
        </Button>
      </div>
      {inviteCode ? (
        <div className="mt-4 flex flex-col gap-2 rounded-2xl bg-slate-50/80 p-4 text-sm text-slate-600">
          <span className="font-semibold text-slate-900">我的邀请码</span>
          <div className="flex items-center justify-between rounded-2xl bg-white px-4 py-3 text-slate-700 shadow-inner">
            <span className="font-mono text-lg">{inviteCode}</span>
        <Button
          onClick={() => onCopy(inviteCode)}
          variant="ghost"
          size="sm"
          className="px-2 text-xs text-blush-500 hover:text-blush-600"
          icon={<ClipboardDocumentListIcon className="h-4 w-4" />}
        >
          复制
        </Button>
          </div>
          <p className="text-xs text-slate-400">分享给伴侣后，对方在下方输入即可完成绑定。</p>
          {copyHint ? <p className="text-xs text-emerald-500">{copyHint}</p> : null}
        </div>
      ) : null}
      <form
        className="mt-4 flex flex-wrap items-center gap-3"
        onSubmit={(event) => {
          event.preventDefault()
          if (joinCode.trim()) {
            onJoin(joinCode.trim())
          }
        }}
      >
        <input
          value={joinCode}
          onChange={(event) => setJoinCode(event.target.value)}
          placeholder="输入对方的邀请码"
          className="h-11 flex-1 rounded-2xl border border-slate-200 px-3 text-sm text-slate-700 focus:border-blush-400 focus:ring-2 focus:ring-blush-100"
        />
        <Button
          type="submit"
          variant="secondary"
          size="sm"
          disabled={loadingJoin}
        >
          {loadingJoin ? '绑定中...' : '加入情侣空间'}
        </Button>
      </form>
    </section>
  )
}

const RelationshipRow = ({ relationship, onLeave }: { relationship: ApiRelationship; onLeave: (relationshipId: number) => void }) => (
  <SwipeableItem
    className="rounded-2xl"
    actionWidth={110}
    actions={
      <div className="flex items-center gap-2 p-2">
        {relationship.status === 'active' ? (
          <button
            className="rounded-2xl bg-amber-500 px-3 py-2 text-xs font-semibold text-white"
            onClick={() => onLeave(relationship.id)}
          >解除</button>
        ) : null}
      </div>
    }
  >
    <div className="flex flex-wrap items-center justify-between gap-2 rounded-2xl border border-slate-100 bg-slate-50/80 px-4 py-3">
      <div>
        <p className="font-semibold text-slate-900">
          {relationship.status === 'active' ? '已绑定情侣' : relationship.status === 'pending' ? '待确认' : '已解除'}
        </p>
        <p className="text-xs text-slate-400">
          创建时间：{dayjs(relationship.created_at ?? undefined).format('YYYY-MM-DD HH:mm')}
        </p>
        {relationship.confirmed_at ? (
          <p className="text-xs text-slate-400">确认时间：{dayjs(relationship.confirmed_at).format('YYYY-MM-DD HH:mm')}</p>
        ) : null}
      </div>
      <KebabMenu
        items={[
          ...(relationship.status === 'active'
            ? [{ label: '解除绑定', onSelect: () => onLeave(relationship.id), danger: true } as const]
            : []),
        ]}
      />
    </div>
  </SwipeableItem>
)

export default RelationshipsPage
